package com.chen.project.white_jotter.controller;

import com.chen.project.white_jotter.pojo.JotterArticle;
import com.chen.project.white_jotter.result.Result;
import com.chen.project.white_jotter.service.admin.JotterArticleService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/api/admin")
public class AdminJotterArticleController {

    @Resource
    private JotterArticleService jotterArticleService;

    // 获取一篇文章
    @GetMapping("/jotter")
    public Result getJotterMdById(Integer id) {
        JotterArticle jotterArticle = jotterArticleService.getJotterMdById(id);
        return new Result(200, "获取MD成功", jotterArticle);
    }

    // 获取一页文章
    @GetMapping("/article")
    public Result getPageArticle(Integer pageNum, Integer pageSize, String query) {
        Map<String, Object> articleMap = jotterArticleService.getPageArticle(pageNum, pageSize, query);
        return new Result(200, "成功获取一页文章", articleMap);
    }

    // 添加文章
    @PostMapping("/article")
    public Result addJotterArticle(@RequestBody JotterArticle jotterArticle) {

        int i = jotterArticleService.addJotterArticle(jotterArticle);
        return new Result(200, "发布文章成功");
    }

    // 修改文章
    @PutMapping("/article/{pageNum}")
    public Result updateArticle(@RequestBody JotterArticle jotterArticle, @PathVariable("pageNum") Integer pageNum) {
        jotterArticleService.updateArticle(jotterArticle);
        return new Result(200, "更新成功");
    }

    // 删除文章
    @DeleteMapping("/article")
    public Result deleteArticle(Integer id) {
        int i = jotterArticleService.deleteArticleById(id);
        return new Result(200, "删除成功");
    }

    @GetMapping("/article/{keyword}")
    public Result search(@PathVariable("keyword") String keyword) {

        Map<String, Object> map = jotterArticleService.search(keyword);
        Integer count = (Integer)map.get("count");
        if(count == 0) return new Result(404, "es没有搜索到", map);

        return new Result(200, "es搜索成功", map);
    }
}
